﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Threading;

namespace Module.Common.Common
{
    public static class GlobalFunction
    {
        // UCCI标准棋子名称，小写为黑方，对应0-15，大写为红方，对应16-31，见GlobalValue.qiZiCnName棋子名称数组
        private static readonly string[] Fen = {
            "k","a","a","b","b","n","n","r","r","c","c","p","p","p","p","p",
            "K","A","A","B","B","N","N","R","R","C","C","P","P","P","P","P"
        };
        public static string QiPanDataToFenStr_header(int[,] QiPan)
        {
            #region 棋盘数据生成FEN字符串
            string output = "";
            for (int i = 0; i < 10; i++) // 行
            {
                string lineString = "";
                int spaceNum = 0;
                for (int j = 0; j < 9; j++) // 列
                {
                    int qz = QiPan[j, i];
                    if (qz == -1)
                    {
                        spaceNum++;
                    }
                    if (qz > -1)
                    {
                        if (spaceNum > 0)
                        {
                            lineString += spaceNum.ToString();
                            spaceNum = 0;
                        }
                        lineString += Fen[qz];
                    }
                }
                if (spaceNum > 0)
                {
                    lineString += spaceNum.ToString();
                }
                output += lineString;
                if (i < 9)
                {
                    output += "/";
                }
            }
            return output;
            #endregion
        }
        /// <summary>
        /// 根据棋盘数据，生成FEN字符串
        /// </summary>
        /// <returns></returns>
        public static string QiPanDataToFenStr(int[,] QiPan, bool SideTag)
        {
            #region 棋盘数据生成FEN字符串
            string output = QiPanDataToFenStr_header(QiPan);
            const bool BLACKSIDE = false;  // 黑方
            //const bool REDSIDE = true;   //红方
            if (SideTag == BLACKSIDE)
            {
                output += " b";
            }
            else
            {
                output += " w";
            }
            output += " - - 0 1";
            //output += GlobalValue.qiPuRecordRoot.Get6Moves();
            return output;
            #endregion
        }
        /// <summary>
        /// 将FEN串信息转换到棋谱数组中
        /// </summary>
        /// <param name="fen">FEN串</param>
        /// <returns>棋谱数组int[9,10]</returns>
        public static int[,] ConvertFenStrToQiPan(string fen)
        {
            int[,] output = new int[9, 10];
            int col, row;
            col = 0;
            row = 0;
            string[] locFen = new string[Fen.Length];
            Array.Copy(Fen, locFen, Fen.Length);

            foreach (char c in fen)
            {
                if (c == '/')
                {
                    row++;
                    col = 0;
                    continue;
                }
                if (char.IsDigit(c)) // 如果是数字
                {
                    int num = (int)Char.GetNumericValue(c);
                    while (num > 0)
                    {
                        output[col, row] = -1;
                        col++;
                        num--;
                    }
                }
                else
                {
                    // 如果是字符
                    int offset = Array.IndexOf(locFen, c + "");
                    output[col, row] = offset;
                    col++;
                    locFen[offset] = "";

                }
            }
            return output;
        }


        /// <summary>
        /// 在浏览器中打开链接
        /// </summary>
        /// <param name="url"></param>
        public static void OpenInBrowser(string url)
        {
            if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                url = url.Replace("&", "^&");
                Process.Start(new ProcessStartInfo("cmd", $"/c start {url}") { CreateNoWindow = true });
            }
        }

        /// <summary>
        /// 延时函数，延时期间可接收和执行事件，解决了系统假死问题
        /// </summary>
        /// <param name="milliSecond"></param>
        public static void Delay(int milliSecond)
        {
            int start = Environment.TickCount;
            while (Math.Abs(Environment.TickCount - start) < milliSecond)
            {
                DispatcherHelper.DoEvents();
            }
        }
        public static class DispatcherHelper
        {
            //[SecurityPermission(SecurityAction.Demand, Flags = SecurityPermissionFlag.UnmanagedCode)]
            public static void DoEvents()
            {
                DispatcherFrame frame = new();
                // Dispatcher的作用是用于管理线程工作项队列，类似于Win32中的消息队列
                Dispatcher.CurrentDispatcher.BeginInvoke(DispatcherPriority.Background, new DispatcherOperationCallback(ExitFrames), frame);
                try { Dispatcher.PushFrame(frame); }
                catch (InvalidOperationException) { }
            }
            private static object ExitFrames(object frame)
            {
                ((DispatcherFrame)frame).Continue = false;
                return null;
            }
        }
    }
}
